package com.bloveoacom.http;

import com.bloveoacom.weichi.BuildConfig;


import org.reactivestreams.Publisher;

import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.bloveoacom.http.HttpApi.BASE_URL;


/**
 * Created by yujunlong on 2016/8/24.
 */

public class HttpMethods {
    public static final int HTTP_SUCCESS = 0;
    public static final int PAGE_SIZE = 10;
    public static final int PAGE_START_SIZE = 1;
    private Retrofit retrofit;
    private HttpService httpService;
    private OkHttpClient okhttpclient;

    //构造方法私有
    private HttpMethods() {
        //手动创建一个OkHttpClient并设置超时时间
        retrofit = getRetrofit(getOkHttpClient(), BASE_URL);
        httpService = retrofit.create(HttpService.class);
    }

    public Retrofit getRetrofit(OkHttpClient client, String baseUrl) {
        return new Retrofit.Builder()
                .client(client)
                .addConverterFactory(MyGsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build();
    }

    public OkHttpClient getOkHttpClient() {
        if (okhttpclient == null) {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            OkHttpUtil.setHttpConfig(httpClientBuilder);
            if (BuildConfig.DEBUG) {
                //设置log拦截器
                httpClientBuilder.addInterceptor(OkHttpUtil.getInterceptor(0));
            }
            okhttpclient = httpClientBuilder.build();
        }
        return okhttpclient;
    }

    //获取单例
    public static HttpMethods getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public static <T> FlowableTransformer<T, T> io_main() {
        return new FlowableTransformer<T, T>() {
            @Override
            public Publisher<T> apply(Flowable<T> upstream) {
                return upstream
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }



    public HttpService getHttpService() {
        return httpService;
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final HttpMethods INSTANCE = new HttpMethods();
    }


}
